<template>
  <div class="home-container">
    <van-nav-bar title="黑马头条" fixed />

    <van-pull-refresh v-model="isLoading" :disabled="finished" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <ArtItem v-for="item in artlist" :key="item.id" :title="item.title" :author="item.aut_name"
          :cmt-count="item.comm_count" :time="item.pubdate" :cover="item.cover">
          <!-- 在使用组件的时候，如果某个属性名是“小驼峰”形式，则绑定属性的时候，建议改写成“连字符”格式。例如： -->
          <!-- cmtCount 建议写成 cmt-count -->
        </ArtItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 按需导入API接口
import { getArticleAPI } from '@/api/articleAPI.js'

import ArtItem from '@/components/ArtItem.vue'

export default {
  name: 'Home',
  data () {
    return {
      // 页码值
      page: 1,
      // 每页显示多少条数据
      limit: 10,
      // 文章的数组
      artlist: [],
      loading: false,
      finished: false,
      isLoading: false
    }
  },
  created () {
    this.initArticleList()
  },
  methods: {
    async initArticleList (isRefresh) {
      const { data: res } = await getArticleAPI(this.page, this.limit)
      // console.log(res)

      if (isRefresh) {
        // / 证明是下拉刷新；新数据在前，旧数据在后
        // this.artlist = [新数据在后, 旧数据在前]
        this.artlist = [...res, ...this.artlist]
        this.isLoading = false
      } else {
        // 证明是上拉加载更多；旧数据在前，新数据在后
        // this.artlist = [旧数据在前, 新数据在后]
        this.artlist = [...this.artlist, ...res]
        this.loading = false
      }
      if (res.length === 0) {
        // 证明没有下一页数据了，直接把 finished 改为 true，表示数据加载完了！
        this.finished = true
      }
    },
    onLoad () {
      // console.log(1)
      this.page++
      this.initArticleList()
    },
    onRefresh () {
      // 1. 让页码值 +1
      this.page++
      // 2. 重新请求接口获取数据
      this.initArticleList(true)
    }
  },
  components: {
    ArtItem
  }
}
</script>

<style lang='less' scoped>
.home-container {
  padding: 46px 0 50px 0;
  .van-nav-bar {
    background-color: #007bff;

    /deep/ .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
